package com.mach.platform.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.mach.platform.domain.Response;
import com.mach.platform.domain.iot.IotSpace;
import com.mach.platform.service.IotSpaceServiceImpl;
import com.mach.platform.service.PicServiceImpl;
import com.mach.platform.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Cleanup;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author Administrator
 * @Description: 后台配置--图片
 * @Package: com.mach.platform.controller
 * @time 2018/7/9 0009 14:13
 */
@Api(tags = { "后台配置--图片" })
@RequestMapping("$pic")
@RestController
public class PicCtrl {

	@Autowired
	private PicServiceImpl      picService;
	@Autowired
	private IotSpaceServiceImpl iotSpaceService;

	/**
	 * 上传图片--关联空间的布局图片
	 *
	 * @param spaceId
	 * @return
	 */
	@ApiOperation(value = "上传图片--关联空间的布局图片", notes = "接口备注：无", produces = "application/json")
	@PostMapping("/upload/{id}")
	public Response uploadPic (
			@ApiParam(name = "spaceId", value = "空间Id", required = true) @PathVariable("id") Long spaceId,
			@ApiParam(name = "pic", value = "固定名称pic", required = true) @RequestParam("pic") MultipartFile file) {

		if (file == null) {
			return Response.error("上传文件为空，上传失败，请检查！");
		}

		//  if upload ? delete old file : ignore                      ------start
		boolean picExits = false;
		String oldUrl = "";
		IotSpace oldone = iotSpaceService.info(spaceId);
		if (oldone.getLayoutPic() != null) {
			picExits = true;
			oldUrl = oldone.getLayoutPic();
		}
		//  if upload ? delete old file : ignore                      ------end

		File finalSave = null;

		try {

			String rootPath = getPicSavePath();

			File targetPath = new File(getPicSavePath(), "/pic");
			if (!targetPath.exists()) {
				targetPath.mkdirs();
			}

			String originalName = file.getOriginalFilename();
			String sufferName = originalName.substring(originalName.lastIndexOf("."));
			String picName = UUIDUtils.generateUUID() + sufferName;

			finalSave = new File(targetPath.getPath() + File.separator + picName);

			// 保存图片
			FileUtils.copyInputStreamToFile(file.getInputStream(), finalSave);

			// 保存地址
			picService.uploadPic(spaceId, finalSave.getAbsolutePath());

			// 删除 旧的文件
			if (picExits) {
				FileUtils.forceDelete(new File(oldUrl));
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return Response.ok(finalSave.getAbsoluteFile());
	}

	/**
	 * 获取 jar包所在 目录路径
	 *
	 * @return
	 */
	public String getPicSavePath ( ) {
		ApplicationHome home = new ApplicationHome(getClass());
		File jarFile = home.getSource();
		return jarFile.getParentFile().getParentFile().getAbsolutePath();
	}

	/**
	 * 访问图片
	 *
	 * @param response
	 * @return
	 */
	@ApiOperation(value = "根据图片url获取图片流", notes = "接口备注：无", produces = "arraybuffer")
	@RequestMapping(value = "visit", method = RequestMethod.POST)
	public void loadPic (HttpServletResponse response,
			@ApiParam(name = "url", value = "图片地址", required = true) @RequestParam("url") String url) {

		try {
			BufferedImage image = ImageIO.read(new File(url));
			String formatName = url.substring(url.lastIndexOf(".") + 1);
			ImageIO.write(image, formatName, response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
			try {
				response.setContentType("application/json;charset=utf-8");
				@Cleanup PrintWriter out = null;
				out = response.getWriter();
				Map map = Maps.newHashMap();
				map.put("status", 408);
				map.put("msg", "图片地址找不到对应文件！");
				out.write(JSON.toJSON(map).toString());
				response.flushBuffer();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

	}

}
